package global

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
	"os"
	"os/signal"
	"server/proto"
	"syscall"
	"time"
)

func init() {
	ViperInit()
	Router = gin.New()
	RpcInit()
}
func ViperInit() {
	path := "D:/gos/src/four/zy/zg_four/client/dev.yaml"
	viper.SetConfigFile(path)
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	Port = viper.GetInt("Port")
	Host = viper.GetString("Host")
}

// todo: 服务发现
func RpcInit() {
	var err error
	ConsulConf := api.DefaultConfig()
	ConsulConf.Address = "127.0.0.1:8500"
	ConsulClient, err = api.NewClient(ConsulConf)
	if err != nil {
		panic(err)
	}
	enter, _, err := ConsulClient.Health().Service("shang", "", true, nil)
	if err != nil {
		panic(err)
	}
	conn, err := grpc.Dial(
		fmt.Sprintf("%s:%d", enter[0].Service.Address, enter[0].Service.Port),
		grpc.WithBlock(),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	if err != nil {
		panic(err)
	}
	RpcClient = proto.NewSerRpcProtoClient(conn)
}

// todo：生成唯一id
func UUidInit() string {
	s := uuid.New()
	return s.String()
}

// todo：健康检查
func ConsulInit(id string) {
	consulClient, err := api.NewClient(api.DefaultConfig())
	if err != nil {
		panic(err)
	}
	service := &api.AgentServiceRegistration{
		ID:      id,
		Name:    "xin",
		Port:    8888,
		Address: "10.2.171.126",
		Check: &api.AgentServiceCheck{
			Interval:                       "3s",
			Timeout:                        "1s",
			HTTP:                           "http://10.2.171.126:8888/index",
			DeregisterCriticalServiceAfter: "30s",
		},
	}
	consulClient.Agent().ServiceRegister(service)
	log.Println("++++++")
}

// todo：运行服务
func WebServerInit() {
	server := &http.Server{
		Addr:    ":8888",
		Handler: Router,
	}
	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			panic(err)
		}
	}()
	id := UUidInit()
	ConsulInit(id)
	fmt.Println(":8888")

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	<-sigChan
	ConsulClient.Agent().ServiceDeregister(id)

	ctx, cencal := context.WithTimeout(context.Background(), time.Second*5)
	defer cencal()
	if err := server.Shutdown(ctx); err != nil {
		//todo: 结束后处理逻辑
		panic(err)
	}
}
